﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.Common;
using DHQGHN.MVC.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Models.Admin;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class ServeyMethodController : BaseController
    {
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ServeyMethodController));
        private ServeyMethodBO serveyBO;
        //
        // GET: /ServeyMothod/
        public ActionResult Index()
        {
            try
            {
                ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;
                ViewBag.ActiveMenus[13] = "active";
                ViewBag.ActiveMenus[225] = "active";
                ServeyMethodModel sModel = new ServeyMethodModel
                {
                    Deleted = 2
                };
                var model = search(sModel, 0, string.Empty);
                return View("~/Views/ServeyMethod/ServeyMethod.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }

        }

        [HttpPost]
        public ActionResult actionSearch(ServeyMethodModel sModel = null, int pageIndex = 0, string sort = "Code", string sortDir = "ASC", string currentId = "-1")
        {
            try
            {
                if (sModel == null) sModel = new ServeyMethodModel();

                var model = search(sModel, pageIndex, currentId);
                return PartialView("~/Views/ServeyMethod/_ServeyList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Chuan bi du lieu Them moi/Cap nhat phuong thuc dieu tra
        /// </summary>
        /// <param name="serveyId">Khoa phuong thuc dieu tra</param>
        /// <returns>View Them moi/Cap nhat phuong thuc</returns>
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdate(string serveyId)
        {
            try
            {
                ServeyMethodModel servey = null;
                if (!String.IsNullOrEmpty(serveyId))
                {
                    serveyBO = new ServeyMethodBO();

                    servey = new ServeyMethodModel(serveyBO.getServeyById(serveyId));
                }
                if (servey == null)
                {
                    servey = new ServeyMethodModel()
                    {
                        Name = string.Empty,
                        Code = string.Empty,
                        Descriptions = string.Empty,
                        Survey_Method_Id = string.Empty
                    };
                }
                if (Request.IsAjaxRequest())
                {
                    return PartialView("~/Views/ServeyMethod/_ServeyModel.cshtml", servey);
                }
                return View(servey);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Them moi/Cap nhat phuong thuc dieu tra
        /// </summary>
        /// <param name="model">Model duoc Them moi/Cap nhat</param>
        /// <returns>Json the hien ket qua xu ly</returns>
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateServey(ServeyMethodModel model)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    serveyBO = new ServeyMethodBO();
                    bool result = serveyBO.createOrUpdateServey(model.toDALModel());
                    if (result)
                    {
                        LogStream.Write<ServeyMethodModel>(GetCurrentUserName(),
                           CommonData.AppName,
                           GetFunction(),
                           Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateServey", model);

                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Save_Success));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Dua phuong thuc dieu tra da xoa vao su dung
        /// </summary>
        /// <param name="serveyId">Khoa phuong thuc dieu tra duoc mo</param>
        /// <returns></returns>
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionActive(string serveyId)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    serveyBO = new ServeyMethodBO();
                    bool result = true;
                    ServeyMethodModel occModel = new ServeyMethodModel(serveyBO.getServeyById(serveyId));
                    occModel.Deleted = 0;
                    serveyBO.createOrUpdateServey(occModel.toDALModel());
                    if (result)
                    {
                        LogStream.Write(GlobalInfo.User.UserName,
                          CommonData.AppName,
                          GetFunction(),
                          CommonData.GetListId(new string[] { serveyId }),
                          Resources.Localization.ActionActiveCaption + " - actionActive");

                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Save_Success));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        /// <summary>
        /// Xoa phuong thuc dieu tra
        /// </summary>
        /// <param name="ids">danh sach khoa cua phuong thuc dieu tra duoc xoa</param>
        /// <returns>Json the hien ket qua xu ly
        /// </returns>
        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(string[] ids)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    serveyBO = new ServeyMethodBO();
                    bool result = serveyBO.deleteServey(ids);

                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId(ids),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200(Resources.Localization.Confirm_Delete_Success));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500(Resources.Localization.Confirm_Save_Error));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }


        /// <summary>
        /// Kiem tra xem Ma phuong thuc da ton tai chua
        /// </summary>
        /// <param name="Code">Ma ung dung</param>
        /// <param name="survey_method_id">Ma phuong thuc dieu tra</param>
        /// <returns>Tra ve thong bao da ton tai neu da ton tai ung dung theo dieu kien dau vao</returns>
        public JsonResult CheckExistServeyCode(string Code, string survey_method_id)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(Code))
                {
                    ServeyMethodModel model = new ServeyMethodModel()
                    {
                        Code = Code
                    };

                    model.Survey_Method_Id = survey_method_id;

                    var dataPage = search(model, 0, string.Empty);
                    var data = dataPage.Data;

                    var surveyCode = Code.Replace(" ", string.Empty).ToLower();

                    for (int i = 0; i < data.Count; i++)
                    {
                        if (surveyCode.Equals(data[i].Code.Replace(" ", string.Empty).ToLower()))
                        {
                            if (!data[i].Survey_Method_Id.Equals(survey_method_id))
                            {
                                isExist = true;
                                break;
                            }
                        }
                    }
                }
                if (isExist)
                {
                    //Thong bao ung dung da ton tai
                    return Json(Resources.Localization.Error_SurveyCodeExist);
                }
                else
                {
                    //Ung dung chua ton tai
                    return Json(true, JsonRequestBehavior.AllowGet);
                }

            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// Kiem tra xem Ten phuong thuc da ton tai chua
        /// </summary>
        /// <param name="Name">Ten phuong thuc</param>
        /// <param name="survey_method_id">Ma Phuong thuc dieu tra</param>
        /// <returns>Tra ve thong bao da ton tai neu da ton tai ung dung theo dieu kien dau vao</returns>
        public JsonResult CheckExistServeyName(string Name, string survey_method_id)
        {
            try
            {
                var isExist = false;
                if (!string.IsNullOrEmpty(Name))
                {
                    ServeyMethodModel model = new ServeyMethodModel()
                    {
                        Name = Name
                    };

                    model.Survey_Method_Id = survey_method_id;

                    var dataPage = search(model, 0, string.Empty);
                    var data = dataPage.Data;

                    var surveyName = Name.Replace(" ", string.Empty).ToLower();

                    for (int i = 0; i < data.Count; i++)
                    {
                        if (surveyName.Equals(data[i].Name.Replace(" ", string.Empty).ToLower()))
                        {
                            if (!data[i].Survey_Method_Id.Equals(survey_method_id))
                            {
                                isExist = true;
                            }
                        }
                    }
                }
                //Kiem tra su ton tai cua ung dung
                //bool check = checkSurveyExist(model);
                if (isExist)
                {
                    //Thong bao ung dung da ton tai
                    return Json(Resources.Localization.Error_SurveyNameExist);
                }
                else
                {
                    //Ung dung chua ton tai
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private bool checkSurveyExist(ServeyMethodModel model)
        {
            try
            {
                if (model == null) model = new ServeyMethodModel();

                if (Request.IsAjaxRequest())
                {
                    serveyBO = new ServeyMethodBO();
                    return serveyBO.checkSurveyExist(model.Survey_Method_Id, model.Code, model.Name);
                }
                return false;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private DataPage<ServeyMethodModel> search(ServeyMethodModel sModel, int pageIndex, string currentId)
        {
            try
            {
                serveyBO = new ServeyMethodBO();
                var DALModel = serveyBO.GetDynamicListPaging(sModel.toDALModel(), PageSize, pageIndex);
                var model = new DataPage<ServeyMethodModel>();
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.ServeyMethodModel servey in lstItem)
                {
                    model.Data.Add(new ServeyMethodModel(servey));
                }

                ServeyMethodModel serveyModel = null;
                if (!String.IsNullOrEmpty(currentId) && model.Data.Count > 0)
                {
                    serveyModel = model.Data.Find(s => s.Survey_Method_Id == currentId);
                    model.CustomData = serveyModel;
                }
                else
                {
                    model.CustomData = sModel;
                }
                if (model.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "ServeyMethod",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "servey-list",

                    };
                    pagNative.TotalRows = model.Data[0].RecordCount;
                    pagNative.CurrentRow = model.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return model;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private string GetFunction()
        {
            return "Danh mục phương thức điều tra";
        }
    }
}